package ${package}.api;

import com.fasterxml.jackson.core.JsonParseException;
import com.ishansong.common.model.Response;
import com.ishansong.log.Loggers;
import org.slf4j.Logger;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.text.SimpleDateFormat;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

/**
 * Author: sid
 * Date:   17/11/23 上午10:04
 */

public abstract class Apis {

    protected final static Logger log = Loggers.get("default");
    /**
     * 默认分页长度
     */
    protected static final Integer DEFAULT_PAGE_SIZE = 10;
    /**
     * 日期类型的格式化 yyyy-MM-dd
     */
    protected static final ThreadLocal<SimpleDateFormat> dateSdf = new ThreadLocal<SimpleDateFormat>() {
        @Override
        protected SimpleDateFormat initialValue() {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            return sdf;
        }
    };
    private String getAllParametersInValidMsg(List<ObjectError> allErrors){
        if(CollectionUtils.isEmpty(allErrors)){
            return "";
        }
        StringBuffer stringBuffer=new StringBuffer();
        for(ObjectError error:allErrors){
            if(null!=error) {
                stringBuffer.append(error.getDefaultMessage() + ",");
            }
        }
        return stringBuffer.toString();
    }
    private String getConstraintViolationsMsg(Set<ConstraintViolation<?>> constraintViolations){
        if(CollectionUtils.isEmpty(constraintViolations)){
            return "";
        }
        StringBuffer stringBuffer=new StringBuffer();
        Iterator<ConstraintViolation<?>> iterable= constraintViolations.iterator();
        while (iterable.hasNext()){
            ConstraintViolation<?> constraintViolation= iterable.next();
            stringBuffer.append(constraintViolation.getMessage()+",");
        }
        return stringBuffer.toString();
    }


    /**
     * 公共异常处理
     * 返回统一的结果
     * @param request
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler
    public Response exception(HttpServletRequest request, Exception ex) {


        String errorMsg=null;

        if(ex instanceof BindException){
            BindException bindException=(BindException)ex;
            errorMsg=this.getAllParametersInValidMsg(bindException.getAllErrors());

        }
        else if(ex instanceof MethodArgumentNotValidException){
            MethodArgumentNotValidException methodArgumentNotValidException=(MethodArgumentNotValidException)ex;
            List<ObjectError> allErrors= methodArgumentNotValidException.getBindingResult().getAllErrors();
            errorMsg=this.getAllParametersInValidMsg(allErrors);

        }
        else if(ex instanceof ConstraintViolationException){
            ConstraintViolationException constraintViolationException=(ConstraintViolationException)ex;
            Set<ConstraintViolation<?>> constraintViolations= constraintViolationException.getConstraintViolations();
            errorMsg=this.getConstraintViolationsMsg(constraintViolations);

        }
        else if(ex instanceof JsonParseException){
            errorMsg="json参数格式错误";
        }
        else if(ex instanceof HttpMessageNotReadableException){
            errorMsg="参数格式错误";
        }
        else {
            errorMsg=ex.getMessage();
        }
        return Response.notOk(errorMsg);
    }
}
